//
//  TreeUIM.m
//  mbstore
//
//  Created by huangyi on 14-3-12.
//  Copyright (c) 2014年 huangyi. All rights reserved.
//

#import "TreeUIM.h"
#import "MBStoreSrv.h"
#import "HomeUI.h"
#import "MBStoreSrv.h"
#import "DicRequest.h"
#define ORANGE [UIColor colorWithRed:1 green:100.0/255.0 blue:38.0/255.0 alpha:1]
@interface TreeUIM ()

@property(nonatomic,strong)NSMutableArray *mainTree;
@property (nonatomic,strong)NSMutableArray *mlIsShow;
@property(nonatomic,strong)NSMutableArray *subTree;

@end

@implementation TreeUIM

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.modalPresentationStyle=UIModalPresentationFormSheet;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout=UIRectEdgeNone;
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    UIButton *cancel=[UIButton buttonWithType:UIButtonTypeCustom];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel sizeToFit];
    [cancel addTarget:self action:@selector(onCancelClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItems=@[cancel.barButtonItem];
    
    
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(HideView:)];
    swipe.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:swipe];
    
    self.tableView.separatorInset=UIEdgeInsetsMake(0, 0, 0, 0);
    self.tableView.rowHeight=60;
    self.title=@"筛选";
    self.strtype=@"";
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChangeTypeNotification:) name:ChangSelcetType object:nil];
    
}
-(void)ChangeTypeNotification:(NSNotification *)notification{
    NSString *strType=(NSString *)notification.object;
    self.strtype=strType;
    if (dicAllType) {
         [self ResetGoodsData:strType];
    }

}
-(void)viewWillAppear:(BOOL)animated{
    if (!dicAllType) {
        MBStoreSrv *mbstroeQuest=[[MBStoreSrv alloc]init];
        [mbstroeQuest GetTree:nil Success:^(NSDictionary *dicReceiveData) {
            dicAllType=dicReceiveData;
            [self ResetGoodsData:self.strtype];
        } Failure:^(NSError *error) {
            
        }];
    }
    if (self.delegate) {
        self.tableView.frame=CGRectMake(0, 0, CGRectGetWidth(self.tableView.bounds), CGRectGetHeight(self.view.frame));
    }
    else{
        self.tableView.frame=CGRectMake(0, CGRectGetMaxY(self.vieType.frame), CGRectGetWidth(self.tableView.bounds), CGRectGetHeight(self.view.frame)-CGRectGetMaxY(self.vieType.frame));
    }
   
}
-(void)ResetGoodsData:(NSString *)strGoods{
    self.mainTree=[NSMutableArray array];
    self.mlIsShow=[NSMutableArray array];
    self.subTree=[NSMutableArray array];
    for (NSString *strKye in [dicAllType allKeys]) {
        [self.mlIsShow addObject:[NSNumber numberWithBool:NO]];
        [self.mainTree addObject:strKye];
        NSArray *arrRelust=[dicAllType objectForKey:strKye];
        NSMutableArray *mlRelust=[[NSMutableArray alloc]init];
        for (int i=0; i<arrRelust.count; i++) {
            MBSearch *mbSearchModel=[MBSearch getMBSearchDictionary:[arrRelust objectAtIndex:i]];
            if ([mbSearchModel.category isEqual:strGoods]||[strGoods isEqual:@""]) {
                [mlRelust addObject:mbSearchModel];
            }
            
        }
        [self.subTree addObject:mlRelust];
        [self.tableView reloadData];
    }
    

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)onCancelClick:(id)sender{
    [self RemoveFormParent:0.3f];
    if (!self.delegate) {
    
    }
    else{
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }//
}

-(void)onScanClick:(id)sender{
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        NSArray *windows=[[UIApplication sharedApplication] windows];
        UIWindow *window=[windows firstObject];
        UINavigationController *nav=(id)window.rootViewController;
        NSArray *controllers=nav.viewControllers;
        HomeUI *home=[controllers firstObject];
        [home openScan];
    }];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.mainTree.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.mlIsShow) {
        if ([[self.mlIsShow objectAtIndex:section]boolValue]) {
            NSArray *subTree=[self.subTree objectAtIndex:section];
            return subTree.count;
        }
        
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return tableView.rowHeight;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier=@"tree";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        cell.clipsToBounds=YES;
    }
    else{
        while ([cell.contentView.subviews lastObject]!=nil) {
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    int idx=indexPath.row;
    cell.accessoryType = UITableViewCellAccessoryNone;
  
    NSArray *subTree=[self.subTree objectAtIndex:indexPath.section];
     MBSearch *mbSearch=[subTree objectAtIndex:idx];
    cell.textLabel.text=mbSearch.subTree;
    cell.textLabel.font=[UIFont systemFontOfSize:16];
    cell.textLabel.textColor=[UIColor blackColor];
    cell.indentationLevel=2;
    cell.indentationWidth=20;
    //    }
    UIView *cellLine=[[UIView alloc]initWithFrame:CGRectMake(0, 59, cell.frame.size.width, 0.5)];
    cellLine.backgroundColor=[UIColor lightGrayColor];
    [cell.contentView addSubview:cellLine];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}
//自定义头部
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIControl *vieResult=[[UIControl alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, CGRectGetHeight([self.tableView rectForHeaderInSection:section]))];
    vieResult.backgroundColor=[UIColor whiteColor];
    [vieResult  addTarget:self action:@selector(HideRow:) forControlEvents:UIControlEventTouchUpInside];
     vieResult.tag=20001+section;
    UILabel *result=[[UILabel alloc]initWithFrame:CGRectMake(20, 0, self.tableView.frame.size.width, vieResult.frame.size.height)];
    result.font=[UIFont boldSystemFontOfSize:18];
    
    
    result.text=[self.mainTree objectAtIndex:section];
    [vieResult addSubview:result];
    
    UIImageView *imgSelect=[[UIImageView alloc]initWithFrame:CGRectMake(self.tableView.frame.size.width-40, 20, 20, 20)];
    imgSelect.image=[UIImage imageNamed:@"treeLeft"];
    [vieResult addSubview:imgSelect];
    UIView *vieLine=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight([self.tableView rectForHeaderInSection:section])-1, self.tableView.frame.size.width, 1)];
    vieLine.backgroundColor=[UIColor lightGrayColor];
    [vieResult addSubview:vieLine];
    return vieResult;
}
-(void)HideRow:(UIControl *)sender{
    UIImageView *imgSender;
    for (UIView *subView in sender.subviews) {
        if ([subView isKindOfClass:[UIImageView class]]) {
            imgSender=(UIImageView *)subView;
        }
    }
    [self.tableView beginUpdates];
    int section=sender.tag-20001;
    BOOL isOpen=NO;
    NSMutableArray* rowToInsert = [[NSMutableArray alloc] init];
	for (int i=0; i<[[self.subTree objectAtIndex:section]count]; i++) {
        NSIndexPath* indexPathToInsert = [NSIndexPath indexPathForRow:i inSection:section];
        [rowToInsert addObject:indexPathToInsert];
    }
    if ([[self.mlIsShow objectAtIndex:section]boolValue]) {
        [self.mlIsShow setObject:[NSNumber numberWithBool:NO] atIndexedSubscript:section];
        imgSender.image=[UIImage imageNamed:@"treeLeft"];
        [self.tableView deleteRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationTop];
    }
    else{
        [self.mlIsShow setObject:[NSNumber numberWithBool:YES] atIndexedSubscript:section];
        imgSender.image=[UIImage imageNamed:@"treedown"];
        
        //        [mlSecRow setObject:[NSString stringWithFormat:@"%d",updateRow] atIndexedSubscript:section];
        [self.tableView insertRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationBottom];
        
        isOpen=YES;
        
        
    }
    [self.tableView endUpdates];
    if (isOpen) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
    
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView reloadData];
    UITableViewCell *cellView = [tableView cellForRowAtIndexPath:indexPath];
    UIView *labLine=[cellView.contentView.subviews objectAtIndex:0];
    labLine.backgroundColor=ORANGE;
    cellView.textLabel.textColor=ORANGE;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    int idx=indexPath.row;
    NSArray *subTree=[self.subTree objectAtIndex:indexPath.section];

    MBSearch *mbSearch=[subTree objectAtIndex:idx];
    if (self.delegate) {
        if ([self.delegate respondsToSelector:@selector(aTreeUIM:onItemClick:)]) {
            [self.delegate aTreeUIM:self onItemClick:mbSearch.catId];
        }
    }
    else{
        [self StartSearch:mbSearch.catId  SearchKey:@""];
    }
    [self RemoveFormParent:0.0f];
}
-(void)StartSearch:(NSString *)catId SearchKey:(NSString *)key{
    MainApp *app=[MainApp mainApp];
    [app.itemList removeAllObjects];
    NSMutableDictionary *mlUserIn=[NSMutableDictionary dictionary];
    NSString *str=@"mainClass";
    if (_segType.selectedSegmentIndex==1) {
        str=@"style";
    }
    [mlUserIn setObject:str forKey:@"type"];
    [mlUserIn setObject:catId forKey:@"catid"];
    [mlUserIn setObject:key forKey:@"searchKey"];
    [[NSNotificationCenter defaultCenter] postNotificationName:ItemListNotification object:self userInfo:mlUserIn];
    
}
- (IBAction)SelectClass:(UISegmentedControl *)sender {
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self StartSearch:@"0" SearchKey:searchBar.text];
    [self RemoveFormParent:0.3f];
    [searchBar resignFirstResponder];
}
- (IBAction)HideView:(id)sender {
    [self RemoveFormParent:0.3f];
}
@end
